<?php


namespace app\api\controller;


use app\admin\model\SystemAdmin;
use app\BaseController;
use app\common\model\Business;
use app\common\model\BusinessDistrict;
use app\common\model\BusinessDistrictAdmin;
use app\common\model\Config;
use app\common\model\Goods;
use app\common\model\GoodsCategory;
use app\common\model\GoodsLibraryGoodsRelation;
use app\common\model\GoodsLibraryShopRelation;
use app\common\model\PointsLog;
use app\common\model\ShopBanner;
use app\common\model\ShopGoods;
use app\common\model\ShopManage;
use app\common\model\User;
use app\common\model\VisitLog;
use EasyAdmin\upload\Uploadfile;
use Intervention\Image\ImageManager;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\Db;
use think\facade\Log;
use think\File;
use think\file\UploadedFile;
use think\helper\Str;
use think\Validate;

class Shop extends BaseController
{
    /**
     * 店铺详情
     */
    public function shopDetail()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'id|店铺id' => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }

        $shop = \app\common\model\Shop::with([
            'district' => function ($query) {
                return $query->field('id,name');
            },
            'banner'   => function ($query) {
                return $query->where('status', 1);
            }
        ])
            ->find($param['id']);


        //获取当前商家的商圈信息
        if ($shop->district_id) {
            $shopIdList = \app\common\model\Shop::where('district_id', $shop->district_id)->column('id');
            $shopIdList = array_values($shopIdList);
        } else {
            $shopIdList = [$param['id']];
        }

        //获取当前店铺可使用积分
        $shop['available_points'] = (new PointsLog())->getUsefulPoints($this->request->uid, $shopIdList);

        if (mb_strlen($shop['name1']) > 15) {
            $shop['name1'] = mb_substr($shop['name1'], 0, 15);
        }
        //当没有设置banner 则展示平台图片  隐藏
//        $shop                     = $shop->toArray();
//        if (!isset($shop['banner']) || !$shop['banner']) {
//            $shop['banner'] = ShopBanner::where('shop_id', 0)->where('status', 1)->select()->toArray();
//        }
        //记录用户访问店铺
        VisitLog::create([
            'user_id' => $this->request->uid,
            'shop_id' => $param['id'],
        ]);
        return success($shop);
    }

    /**
     * 店铺的首页产品
     */
    public function shopProduct()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'id|店铺id'         => 'require|number',
            'price_low|最低价'  => 'number',
            'price_high|最高价' => 'number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shopId = $param['id'];
        [$page_size, $page_no] = paginate($param);
        //商家所有商品id
//        $self = Goods::getShopGoodsIdList($shopId);
        //获取店铺商品
        $data = new Goods();
//        if ($self) {
//            $data = $data->where('id', 'in', $self);
//        } else {
//        $data = $data;
//        }
        if (isset($param['price_low']) && $param['price_low']) {
            $data = $data->where('price_low', '>=', $param['price_low']);
        }
        if (isset($param['price_high']) && $param['price_high']) {
            $data = $data->where('price_high', '<=', $param['price_high']);
        }
        if (isset($param['sort']) && $param['sort']) {
            $data->order('price_low', $param['sort']);
        }



        $list = $data->where('shop_id', $shopId)->where('status', 1)
            ->where('is_sale', 1)
            ->order('is_share', 'asc')
            ->order('shop_id', 'desc')
            ->field('id,img,name,show_price')
            ->limit($page_size * $page_no, $page_size)->select();

        if (count($list) == 0) {
            //店铺是否开启共享库
            $shop = \app\common\model\Shop::find($shopId);
            if ($shop && $shop->share_goods_switch == 1) {
                //查询的商品id
                $shareGoodsId = GoodsLibraryGoodsRelation::alias('gr')
                    ->join('pm_shop_goods sg', 'gr.goods_id = sg.goods_id', 'left')
                    ->where('gr.goods_library_id', 2)
                    ->where('gr.status', 1)
                    ->where('gr.delete_time', 0)
                    ->where('sg.shop_id', $shopId)
                    ->where('sg.status', 1)
                    ->column('sg.goods_id');

                $list = $data->where('status', 1)
                    ->where('is_sale', 1)
                    ->where('id', 'in', $shareGoodsId)
                    ->order('is_share', 'asc')
                    ->order('shop_id', 'desc')
                    ->field('id,img,name,show_price')
                    ->limit($page_size * $page_no, $page_size)->select();
            }
            
            if (count($list) == 0) {
                //查询工具库的商品id
                $platformGoodsId = GoodsLibraryGoodsRelation::alias('gr')
                    ->join('pm_shop_goods sg', 'sg.goods_id = gr.goods_id', 'left')
                    ->where('gr.goods_library_id', 1)
                    ->where('gr.status', 1)
                    ->where('gr.delete_time', 0)
                    ->where('sg.shop_id', $shopId)
                    ->where('sg.status', 1)
                    ->where('sg.goods_shop_id', 0)
                    ->column('sg.goods_id');

                $list = $data->where('status', 1)
                    ->where('is_sale', 1)
                    ->where('id', 'in', $platformGoodsId)
                    ->order('is_share', 'asc')
                    ->order('shop_id', 'desc')
                    ->field('id,img,name,show_price')
                    ->limit($page_size * $page_no, $page_size)
                    ->select();

                if (count($list) == 0) {
                    //查询工具库的商品id
                    $everyGoodsId = GoodsLibraryGoodsRelation::alias('gr')
                        ->join('pm_shop_goods sg', 'sg.goods_id = gr.goods_id', 'left')
                        ->where('gr.status', 1)
                        ->where('gr.delete_time', 0)
                        ->where('sg.shop_id', $shopId)
                        ->where('sg.status', 1)
                        ->where('sg.goods_shop_id', 0)
                        ->column('sg.goods_id');

                    $list = $data->where('status', 1)
                        ->where('is_sale', 1)
                        ->where('id', 'in', $everyGoodsId)
                        ->order('is_share', 'asc')
                        ->order('shop_id', 'desc')
                        ->field('id,img,name,show_price')
                        ->limit($page_size * $page_no, $page_size)
                        ->select();
                }
            }
        }
        return success($list);
    }

    /**
     * 获取商家赠送积分页面数据
     */
    public function getBusinessPoints()
    {
        //搜索当前用户的商家信息
//        $business = Business::where('user_id', $this->request->uid)->find();
//        if (!$business) {
//            return error('当前用户不是商家');
//        }
//        $shopList = \app\common\model\Shop::with([
//            'banner' => function ($query) {
//                $query->limit(1);
//            }
//        ])->where('business_id', $business->id)->select();
        Log::error(var_export($this->request->param(), true));
        $user_id = $this->request->uid;
        $user_info = $this->request->user_info;
//        if (!in_array($user_info->role, [1, 2])) {
//            return error('当前用户没有操作权限');
//        }
//        if ($user_info->role == 1) { //店铺老板, 多家店铺
//            $shopList = \app\common\model\Shop::with([
//                'banner' => function ($query) {
//                    $query->limit(1);
//                }
//            ])->where('user_id', $user_id)->where('status', 1)->select();
//        } else {
//            $shopList = \app\common\model\Shop::with([
//                'banner' => function ($query) {
//                    $query->limit(1);
//                }
//            ])->where('id', $user_info->shop_id)->where('status', 1)->select();
//        }
//        if (!$shopList) {
//            return error('没有可用店铺信息');
//        }
        $shopIdList = ShopManage::where('user_id', $user_id)
            ->where('status', 1)->column('shop_id');
        $shopList = [];
        if ($shopIdList) {
            $shopList = \app\common\model\Shop::with([
                'banner' => function ($query) {
                    $query->limit(1);
                }
            ])->where('id', 'in', $shopIdList)->select();
        }

        $toUser = '';
        //获取收取积分用户信息
//        $toUserId = explode('=', input('to_user_id'))[1];
        $toUserId = input('to_user_id', 0);
//        Log::error();
        if ($toUserId) {
            $toUser = User::findOrEmpty($toUserId);
        }

        $data['to_user_info'] = $toUser;
        $data['shop_list'] = $shopList;
        return success($data);
    }

    /**
     * 发送积分
     * 判断当前用户权限  权限修改了逻辑
     *
     */
    public function sendPoints()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id'    => 'require|number',
            'to_user_id|用户id' => 'require|number',
            'num|赠送积分数量'  => 'require|number|>:0',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shopId = $param['shop_id'];
        $toUserId = $param['to_user_id'];
        $num = $param['num'];
        $userId = $this->request->uid;
        $manage = ShopManage::where('shop_id', $shopId)->where('user_id', $userId)
            ->where('status', 1)
            ->find();
        if (!$manage) {
            return error('当前用户没有权限');
        }
        //判断发送积分是否在权限范围内
        if (!strstr($manage->function_arr, "3")) {
            return error('当前用户权限不足');
        }

        $shop = \app\common\model\Shop::find($shopId);
        if (!$shop) {
            return error('店铺信息异常');
        }

        //判断店铺积分剩余
        if ($shop->points_one - $num < $shop->point_limit) {
            return error('当前店铺积分不足');
        }

        //赠送积分
        Db::startTrans();
        try {
            //添加记录
            $shop->points_one -= $num;
            $shop->save();
            //用户收款信息
            PointsLog::create([
                'form_user_id' => $userId,
                'user_id'      => $toUserId,
                'shop_id'      => $shopId,
                'num'          => $num,
                'type'         => 1,
                'flag'         => 1,
                'expire_time'  => time() + Config::getSelfConfig('积分有效时长'),
            ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return error($e->getMessage());
        }
        return success('赠送成功');
    }

    /**
     * 商家入驻申请
     * 用户申请店铺入驻
     *  1.直接生成店铺信息,需要后台审核
     *  2. 后台审核通过后,
     *      生成对应的后台商家账户,
     *      修改当前申请人的身份和对应管理店铺的id
     */
    public function apply()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_name|店铺名称' => 'require',
            'contacts|联系人'    => 'require',
            'phone|联系人电话'   => 'require|mobile',
            'address|店铺地址'   => 'require'
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user_id = $this->request->uid;
        $user_info = $this->request->user_info;
        //判断当前账号是否申请过店铺
        $a = \app\common\model\Shop::where('user_id', $user_id)->find();
        if ($a) {
            return error('当前用户已经申请过店铺,请勿重复提交');
        }
        //判断这个联系人是否存在,是否已经是店铺老板
        $phone = $param['phone'];
        $admin = SystemAdmin::where('username', $phone)->find();
//        $boss_id = 0;
        if ($admin) {
            if ($admin->auth_ids != 7) {
                return error('当前联系人已在系统中存在其他角色');
            }

            //搜索 后台id 来找到店铺老板
            $boss_id = User::where('admin_id', $admin->id)->value('id');
            if (!$boss_id) {
                $user_info->admin_id = $admin->id;
                $user_info->role = 1;
                $user_info->save();
                $boss_id = $user_id;
            }
        } else {
            $admin = SystemAdmin::create([
                'auth_ids' => 7,
                'username' => $phone,
                'password' => password($phone),
                'phone'    => $phone,
                'remark'   => $param['contacts'],
                'status'   => 0,
            ]);
            $boss_id = $user_id;
            $user_info->admin_id = $admin->id;
            $user_info->role = 1;
            $user_info->save();
        }
        //创建shop信息
        $shop = \app\common\model\Shop::create([
            'user_id'   => $boss_id,
            'name'      => $param['shop_name'],
            'phone'     => $phone,
            'address'   => $param['address'],
            'shop_code' => Str::random(6, 2),
            'logo'      => isset($param['logo']) ? $param['logo'] : '',
        ]);

        return success([], '提交成功,请耐心等待审核!');
    }


    /**
     * 商品页面
     * 商品分类
     */
    public function categoryList()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺ID' => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shopId = $param['shop_id'];
        //获取店铺信息
        $shop = \app\common\model\Shop::find($shopId);
        $list[] = [
            "id"      => 0,
            "shop_id" => $shopId,
            "name"    => "全部",
            "sort"    => 0,
            "type"    => 0,
        ];
        $list[] = [
            "id"      => 1,
            "shop_id" => $shopId,
            "name"    => $shop->self_name ?: "自营",
            "sort"    => 1,
            "type"    => 0,
        ];

        if ($shop->share_goods_switch == 1) {
            $list[] = [
                "id"      => 2,
                "shop_id" => $shopId,
                "name"    => $shop->share_name ?: "共享",
                "sort"    => 2,
                "type"    => 2,
            ];
        }

        if ($shop->platform_goods_switch == 1) {
            $list[] = [
                "id"      => 3,
                "shop_id" => $shopId,
                "name"    => $shop->platform_name ?: "工具",
                "sort"    => 3,
                "type"    => 1,
            ];
        }

        //搜索商家是否可以展示其他库
        $re = GoodsLibraryShopRelation::with('goods_library')
            ->where('shop_id', $shopId)->where('status', 1)->select();
        foreach ($re as $k => $v) {
            if ($v->goods_library->status == 0) {
                continue;
            }
            $list[] = [
                "id"      => 4 + $k,
                "shop_id" => $shopId,
                "name"    => $v->goods_library->name ?: "福利库",
                "sort"    => 4 + $k,
                "type"    => $v->goods_library_id,
            ];
        }
//        //全部 获取全部商品的所有分类
//        $self       = Goods::where('shop_id', $shopId)->column('id');
//        $additional = ShopGoods::where('shop_id', $shopId)->column('goods_id');
//        foreach ($additional as $v) {
//            $self[] = $v;
//        }
        /**
         * 小程序不需要展示分类,只需判断用户是否展示 自营,共享,平台
         */
        //全部 以及相对应的分类
//        $cateList = Goods::alias('g')
//            ->join('pm_goods_category gc', 'g.category_id = gc.id', 'left')
//            ->where('g.id', 'in', $self)
//            ->group('category_id')
//            ->field('gc.id,gc.name')
//            ->select();
//
//        $list[] = [
//            "id"            => 0,
//            "shop_id"       => $param['shop_id'],
//            "name"          => "全部",
//            "sort"          => 0,
//            'category_list' => $cateList
//        ];
//        //店铺自营 以及相对应的分类
//        $list[] = [
//            "id"            => 1,
//            "shop_id"       => $param['shop_id'],
//            "name"          => "店铺自营",
//            "sort"          => 0,
//            "category_list" => []
//        ];
//        //共享产品 以及相对应的分类
//        $cateList1 = Goods::alias('g')
//            ->join('pm_goods_category gc', 'g.category_id = gc.id', 'left')
//            ->where('g.id', 'in', $additional)
//            ->where('is_share', 1)
//            ->group('category_id')
//            ->field('gc.id,gc.name')
//            ->select();
//        $list[]    = [
//            "id"            => 2,
//            "shop_id"       => $param['shop_id'],
//            "name"          => "共享产品",
//            "sort"          => 0,
//            "category_list" => $cateList1
//        ];
//        //平台产品 以及相对应的分类
//        $cateList2 = Goods::alias('g')
//            ->join('pm_goods_category gc', 'g.category_id = gc.id', 'left')
//            ->where('g.id', 'in', $additional)
//            ->where('is_share', 0)
//            ->group('category_id')
//            ->field('gc.id,gc.name')
//            ->select();
//        $list[]    = [
//            "id"            => 2,
//            "shop_id"       => $param['shop_id'],
//            "name"          => "平台产品",
//            "sort"          => 0,
//            "category_list" => $cateList2
//        ];

        return success($list);
    }

    /**商品页面
     *商品列表
     */
    public function productList()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺ID'   => 'require|number',
            'category_id|分类' => 'require|number',
            'type|类型'        => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $categoryId = $param['category_id'];
        $type = $param['type'];
        $shopId = $param['shop_id'];
        [$page_size, $page_no] = paginate($param);
        //获取店铺信息
        $shop = \app\common\model\Shop::find($shopId);

        //全部
        if ($categoryId == 0) {
            //获取店铺所有商品id
            //自营
            $goodsIdList = \app\common\model\Goods::where('shop_id', $shopId)->where('status', 1)->column('id');

            //共享库
            $shareGoodsId = [];
            if ($shop->share_goods_switch == 1) {
                $shareGoodsId = GoodsLibraryGoodsRelation::alias('gr')
                    ->join('pm_shop_goods sg', 'gr.goods_id = sg.goods_id', 'left')
                    ->where('gr.goods_library_id', 2)
                    ->where('gr.status', 1)
                    ->where('gr.delete_time', 0)
                    ->where('sg.shop_id', $shopId)
                    ->where('sg.status', 1)
                    ->column('sg.goods_id');
            }
            //工具库
            $platformGoodsId = [];
            if ($shop->platform_goods_switch == 1) {
                $platformGoodsId = GoodsLibraryGoodsRelation::alias('gr')
                    ->join('pm_shop_goods sg', 'sg.goods_id = gr.goods_id', 'left')
                    ->where('gr.goods_library_id', 1)
                    ->where('gr.status', 1)
                    ->where('gr.delete_time', 0)
                    ->where('sg.shop_id', $shopId)
                    ->where('sg.status', 1)
                    ->where('sg.goods_shop_id', 0)
                    ->column('sg.goods_id');
            }

            //其他所有库中
            //搜索用户添加其他库中商品
            $goods_list2 = ShopGoods::where('status', 1)
                ->where('shop_id', $shopId)->column('goods_id');
            $libraryGoodsId = GoodsLibraryShopRelation::alias('sr')
                ->join('pm_goods_library_goods_relation gr', 'sr.goods_library_id = gr.goods_library_id', 'left')
//                ->where('gr.goods_library_id','not in',[1,2])
                ->where('sr.shop_id', $shopId)
                ->where('sr.status', 1)
                ->where('gr.status', 1)
                ->where('gr.goods_id', 'in', $goods_list2)
                ->where('sr.delete_time', 0)
                ->column('gr.goods_id');
            $goods_id_list = $libraryGoodsId + $goodsIdList + $platformGoodsId + $shareGoodsId;
        } elseif ($categoryId == 1) { //自营
            $goods_id_list = Goods::where('shop_id', $shopId)->where('status', 1)->column('id');
        } elseif ($categoryId == 2) { //共享
            //共享库
            if ($shop->share_goods_switch == 1) {
                $goods_id_list = GoodsLibraryGoodsRelation::alias('gr')
                    ->join('pm_shop_goods sg', 'gr.goods_id = sg.goods_id', 'left')
                    ->where('gr.goods_library_id', 2)
                    ->where('gr.status', 1)
                    ->where('gr.delete_time', 0)
                    ->where('sg.shop_id', $shopId)
                    ->where('sg.status', 1)
                    ->column('sg.goods_id');
            }
        } elseif ($categoryId == 3) { //工具
            if ($shop->platform_goods_switch == 1) {
                $goods_id_list = GoodsLibraryGoodsRelation::alias('gr')
                    ->join('pm_shop_goods sg', 'sg.goods_id = gr.goods_id', 'left')
                    ->where('gr.goods_library_id', 1)
                    ->where('gr.status', 1)
                    ->where('gr.delete_time', 0)
                    ->where('sg.shop_id', $shopId)
                    ->where('sg.status', 1)
                    ->where('sg.goods_shop_id', 0)
                    ->column('sg.goods_id');
            }
        } else {
            //获取库中相对应产品id
            $library_id_list = GoodsLibraryGoodsRelation::alias('gr')
                ->join('pm_goods_library_shop_relation sr', 'gr.goods_library_id = sr.goods_library_id', 'right')
                ->where('gr.goods_library_id', $type)
                ->where('gr.status', 1)
                ->where('sr.shop_id', $shopId)
                ->where('sr.status', 1)
                ->where('sr.delete_time', 0)
                ->column('gr.goods_id');
            $goods_id_list = [];
            if ($library_id_list) {
                //查询用户添加产品id
                $goods_id_list = ShopGoods::where('shop_id', $shopId)->where('status', 1)->where('goods_id', 'in', $library_id_list)->column('goods_id');
            }

        }
//        //如果是平台商品
//        if ($type == 0) {
//            //固有的商品库
//            //全部
//            if ($categoryId == 0) {
//                $goods_id_list = Goods::getShopGoodsIdList($shopId);
//            }
//            //自营
//            if ($categoryId == 1) {
//                $goods_id_list = Goods::where('shop_id', $shopId)->where('status', 1)->column('id');
//            }
//            //共享
//            if ($categoryId == 2) {
//                //
//                $goods_id_list = ShopGoods::where('shop_id', $shopId)->where('goods_shop_id', '<>', 0)->column('id');
//            }
//            //平台
//            if ($categoryId == 3) {
//                $goods_id_list = ShopGoods::where('shop_id', $shopId)->where('goods_shop_id', 0)->column('id');
//            }
//        } else {
//            //特殊商品库
//            $goods_id_list = GoodsLibraryGoodsRelation::where('goods_library_id', $type)->column('id');
//        }
//        dd($goods_id_list);
        $goods = Goods::where('id', 'in', $goods_id_list)->where('status', 1)->where('is_sale', 1);
        if (isset($param['sort'])) {
            if ($param['sort'] == 1) {
                $sort = 'asc';
            } elseif ($param['sort'] == 2) {
                $sort = 'desc';
            }
            if (isset($sort) && $sort) {
                $goods = $goods->order('price_low', $sort);
            }
        }
        $list = $goods->order('sort', 'desc')->limit($page_size * $page_no, $page_size)->select();
        return success($list);
    }

    /**
     * 根据商圈获取当前店铺列表
     */
    public function shopListByDistrict()
    {
        //检测当前用户是否为商圈管理者
        $re = BusinessDistrictAdmin::where('user_id', $this->request->uid)->find();
        if (!$re) {
            return error('没有可管理的商圈');
        }
        $list = \app\common\model\Shop::where('district_id', $re->district_id)->select();
        return success($list);
    }

    /**
     * 积分2转积分1  废弃
     * 积分转换
     */
//    public function pointsExchange()
//    {
//        $param    = $this->request->param();
//        $validate = new Validate();
//        $validate->rule([
//            'shop_id|店铺ID' => 'require|number',
//            'num|数量'       => 'require|number'
//        ]);
//        if (!$validate->check($param)) {
//            return error($validate->getError());
//        }
//        $user_id = $this->request->uid;
//        $shop_id = $param['shop_id'];
//        $num     = $param['num'];
//        $shop    = \app\common\model\Shop::with('business')->find($shop_id);
//        //判断当前用户是否是店铺老板
//        if ($user_id != $shop->business->user_id) {
//            return error('当前用户无操作权限');
//        }
//        //判断当前店铺积分2是否足够
//        if ($num > $shop->points_two) {
//            return error('当前店铺积分不足');
//        }
//        Db::startTrans();
//        try {
//            //执行积分转换
//            $shop->points_two -= $num;
//            $shop->points_one += $num;
//            $shop->save();
//            //记录
//            PointsLog::create([
//                'user_id' => $user_id,
//                'shop_id' => $shop_id,
//                'num'     => $num,
//                'type'    => 3,
//                'flag'    => 5
//            ]);
//            Db::commit();
//        } catch (\Exception $e) {
//            Db::rollback();
//            return error();
//        }
//        return success([], '积分转换成功');
//    }

    /**
     * 商圈管理员去店铺结算积分
     */
    public function settlementDistrict()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shop_id = $param['shop_id'];
        $user_id = $this->request->uid;
        //鉴权 判断当前用户是否有操作权限
        $shop = \app\common\model\Shop::where('status', 1)->find($shop_id);
        if (!$shop) {
            return error('当前店铺已关闭');
        }
        if (!$shop->district_id) {
            return error('当前店铺不在商圈中');
        }
        $admin = BusinessDistrictAdmin::where('user_id', $user_id)->where('district_id', $shop->district_id)->find();
        if (!$admin) {
            return error('当前用户没有操作权限');
        }
        //拿到店铺当前积分
        $num = $shop->points_one;
        if ($num > 0) {
            $type = 5;
        } else {
            $type = 4;
        }
        //进行归零操作
        Db::startTrans();
        try {
            $shop->points_one = 0;
            $shop->save();
            //记录
            PointsLog::create([
                'user_id' => $user_id,
                'shop_id' => $shop_id,
                'num'     => -$num,
                'type'    => $type,
                'flag'    => 3
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return error($e->getMessage());
        }
        return success([], '结算成功');
    }

    /**
     * 商圈核算
     */
    public function checkPoints()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shop_id = $param['shop_id'];
        $user_id = $this->request->uid;
        //鉴权 判断当前用户是否有操作权限
        $shop = \app\common\model\Shop::where('status', 1)->find($shop_id);
        if (!$shop) {
            return error('当前店铺已关闭');
        }
        if (!$shop->district_id) {
            return error('当前店铺不在商圈中');
        }
        $admin = BusinessDistrictAdmin::where('user_id', $user_id)->where('district_id', $shop->district_id)->find();
        if (!$admin) {
            return error('当前用户没有操作权限');
        }

        //总共发出的积分
        $send_num = PointsLog::where('shop_id', $shop_id)
            ->where('type', 1)
            ->where('flag', 1)
            ->sum('num');

        //总共收入积分
        $income_num = PointsLog::where('shop_id', $shop_id)
            ->where('type', 2)
            ->where('flag', 2)
            ->sum('num');

        //商家结算总金额
        $settlement_num = PointsLog::where('shop_id', $shop_id)
            ->where('type', 'in', [4, 5])
            ->where('flag', 3)
            ->sum('num');
        $total_points = $income_num - $send_num + $settlement_num;
        $shop->points_one = $total_points;
        $shop->save();
        return success(['total_points' => $total_points]);
    }

    /**
     * 商家详情页面接口
     * 商圈管理员给店铺核算的页面接口
     */
    public function shopCheckDetail()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shop_id = $param['shop_id'];
        $shop = \app\common\model\Shop::where('status', 1)
            ->find($shop_id);
        return success($shop);
    }

    /**
     * 商家积分统计
     */
    public function shopPointsSummary()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        if (isset($param['time_flag']) && $param['time_flag']) {
            switch ($param['time_flag']) {
                case 1: //当月
                    $start_time = mktime(0, 0, 0, date('m'), 1, date('Y'));
                    break;
                case 2: //最近一个月
                    $start_time = mktime(0, 0, 0, date('m') - 1, date('d'), date('Y'));
                    break;
                case 3://最近三个月
                    $start_time = mktime(0, 0, 0, date('m') - 3, date('d'), date('Y'));
                    break;
                case 4://最近六个月
                    $start_time = mktime(0, 0, 0, date('m') - 6, date('d'), date('Y'));
                    break;
                default:
                    $start_time = mktime(0, 0, 0, date('m') - 1, date('d'), date('Y'));
                    break;
            }
        } else {
            $start_time = mktime(0, 0, 0, date('m') - 1, date('d'), date('Y'));
        }
        $shop_id = $param['shop_id'];
        $shop = \app\common\model\Shop::find($shop_id);
        //统计店铺总赠送 和 总兑换
        //总赠送
        $sendPoints = PointsLog::where('shop_id', $shop_id)
            ->where('type', 1)
            ->where('flag', 1)
            ->sum('num');
        //总兑换
        $usePoints = PointsLog::where(function ($query) use ($shop_id) {
            $query->where(['shop_id' => $shop_id, 'goods_shop_id' => 0])->whereOr('goods_shop_id', $shop_id);
        })->where('create_time', '>=', $start_time)
            ->where('type', 2)
            ->where('flag', 2)
            ->sum('num');
        $data = [
            'shop'        => $shop,
            'send_points' => $sendPoints,
            'use_points'  => $usePoints
        ];
        return success($data);
    }

    /**
     * 商家积分流水
     */
    public function shopPointsLog()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        if (isset($param['time_flag']) && $param['time_flag']) {
            switch ($param['time_flag']) {
                case 1: //当月
                    $start_time = mktime(0, 0, 0, date('m'), 1, date('Y'));
                    break;
                case 2: //最近一个月
                    $start_time = mktime(0, 0, 0, date('m') - 1, date('d'), date('Y'));
                    break;
                case 3://最近三个月
                    $start_time = mktime(0, 0, 0, date('m') - 3, date('d'), date('Y'));
                    break;
                case 4://最近六个月
                    $start_time = mktime(0, 0, 0, date('m') - 6, date('d'), date('Y'));
                    break;
                default:
                    $start_time = mktime(0, 0, 0, date('m') - 1, date('d'), date('Y'));
                    break;
            }
        }
        $shop_id = $param['shop_id'];
        [$page_size, $page_no] = paginate($param);
//        $log = PointsLog::with([
//            'user'    => function ($query) {
//                $query->field('id,nickname,portrait');
//            },
//            'order_r' => function ($query) {
//                $query->with(['goods' => function ($query) {
//                    $query->field('id,name,img');
//                }])->field('id,goods_id');
//            }
//        ])
        $log = PointsLog::alias('pl')
            ->join('pm_user u', 'pl.user_id = u.id', 'left')
            ->join('pm_order o', 'pl.relation_id = o.id', 'left')
            ->join('pm_user u1', 'pl.form_user_id = u1.id', 'left')
            ->where(function ($query) use ($shop_id) {
                $query->where(['pl.shop_id' => $shop_id, 'pl.goods_shop_id' => 0])->whereOr('pl.goods_shop_id', $shop_id);
            });

        if (isset($start_time) && $start_time) {
            $log = $log->where('pl.create_time', '>', $start_time);
        }

        $log = $log->order('pl.id', 'desc')
            ->limit($page_size * $page_no, $page_size)
            ->field('pl.*,u.nickname,u.portrait,o.id as order_id,o.receive_time,u1.nickname as form_nickname,u1.phone as form_phone')
            ->select();

        $nextPage = true;
        if (count($log) < $page_size) {
            $nextPage = false;
        }
        foreach ($log as $k => &$v) {
            switch ($v->flag) {
                case 1:
                    $v->type = 2; //1:增加  2:减少
                    $v->type_name = "商家赠送";
                    break;
                case 2:
                    $v->type = 1;//
                    $v->type_name = "兑换商品";
                    break;
                case 3:
                    if ($v->type = 4) {
                        $v->type = 1;
                    } else {
                        $v->type = 2;
                    }
                    $v->type_name = "商家结算";
                    break;
                case 4:
                    $v->type = 2;
                    $v->type_name = "商家提现";
                    break;
                case 5:
                    $v->type = 2;
                    $v->type_name = "商家退款";
                    break;
                default:
                    $v->type = 0;
                    $v->type_name = "未知";
                    break;
            }
            if ($v->order_id) {
                if ($v->goods_shop_id == 0) {
                    $v->num = 0;
                }
                if ($v->receive_time == 0) {
                    unset($log[$k]);
                }
            }
            if (mb_strlen($v->form_nickname) > 4) {
                $v->form_nickname = mb_substr($v->form_nickname, 0, 4);
            }
        }
        if ($log->toArray()) {
            $log = array_values($log->toArray());
        }

        $data = [
            'next_page_flag' => $nextPage,
            'list'           => $log,
        ];
        return success($data);
    }

    /**
     * 导出 excel
     * 结算明细
     */
    public function export()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id'     => 'require|number',
            'time_flag|时间标识' => 'require',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }

        switch ($param['time_flag']) {
            case 1: //当月
                $start_time = mktime(0, 0, 0, date('m'), 1, date('Y'));
                break;
            case 2: //最近一个月
                $start_time = mktime(0, 0, 0, date('m') - 1, date('d'), date('Y'));
                break;
            case 3://最近三个月
                $start_time = mktime(0, 0, 0, date('m') - 3, date('d'), date('Y'));
                break;
            case 4://最近六个月
                $start_time = mktime(0, 0, 0, date('m') - 6, date('d'), date('Y'));
                break;
            default:
                $start_time = mktime(0, 0, 0, date('m') - 1, date('d'), date('Y'));
                break;
        }

        $shop_id = $param['shop_id'];
        //获取店铺信息
        $shopInfo = \app\common\model\Shop::find($shop_id);
        if (!$shopInfo) {
            return error('店铺信息异常');
        }
        [$page_size, $page_no] = paginate($param);
        $list = PointsLog::with([
            'user'    => function ($query) {
                $query->field('id,nickname,portrait,phone');
            },
            'order_r' => function ($query) {
                $query->with([
                    'goods' => function ($query) {
                        $query->field('id,name,img');
                    }
                ])->field('id,goods_id,name,phone,order_no');
            }
        ])
            ->where(function ($query) use ($shop_id) {
                $query->where(['shop_id' => $shop_id, 'goods_shop_id' => 0])->whereOr('goods_shop_id', $shop_id);
            })
            ->where('create_time', '>', $start_time)
            ->order('id', 'desc')
            ->limit($page_size * $page_no, $page_size)
            ->select();


        foreach ($list as &$v) {
            switch ($v->type) {
                case 1: //用户增加
                    $v->type_name = '减少';
                    break;
                case 2: //用户减少
                    $v->type_name = '增加';
                    break;
                case 3: //用户不变
                    $v->type_name = '不变';
                    break;
                case 4: //商户增加
                    $v->type_name = '增加';
                    break;
                case 5: //商户减少
                    $v->type_name = '减少';
                    break;
                default:
                    $v->type_name = '异常';
                    break;
            }
            switch ($v->flag) { //1:商家赠送 2:兑换商品 3:商家结算 4:商家提现  5:商家退款
                case 1:
                    $v->flag_name = '商家赠送';
                    break;
                case 2:
                    $v->flag_name = '兑换商品';
                    break;
                case 3:
                    $v->flag_name = '商家结算';
                    break;
                case 4:
                    $v->flag_name = '商家提现';
                    break;
                case 5:
                    $v->flag_name = '商家退款';
                    break;
                default:
                    $v->flag_name = '异常';
                    break;
            }
            $v->create_time = date('Y-m-d H:i:s', $v->create_time);
        }
        $fileName = date('YmdHis');

        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(public_path() . '积分流水导出模板.xls');
        $sheet = $spreadsheet->getActiveSheet();
        $startLine = 2;
        $line = $startLine;
        foreach ($list as $k => $l) {
            $goods_name = '';
            if (isset($l->order_r) && isset($l->order_r->goods) && $l->order_r->goods) {
                $goods_name = $l->order_r->goods->name;
            }
            $sheet->setCellValue('A' . $line, $shopInfo['name']);
            $sheet->setCellValue('B' . $line, $l['create_time']);
            $sheet->setCellValue('C' . $line, $l['num']);
            $sheet->setCellValue('D' . $line, $l['type_name']);
            $sheet->setCellValue('E' . $line, $l['flag_name']);
            $sheet->setCellValue('F' . $line, isset($l->order_r) ? $l->order_r->order_no : '');
            $sheet->setCellValue('G' . $line, isset($l->user) ? $l->user->nickname : '');
            $sheet->setCellValue('H' . $line, isset($l->user) ? $l->user->phone : '');
            $sheet->setCellValue('I' . $line, $goods_name);
            $line++;
        }
        $filePath = public_path() . 'download/' . $fileName . '.xls';
        $writer = IOFactory::createWriter($spreadsheet, 'Xls');
        $writer->save($filePath);
        return success([
            'file_url' => $this->request->domain() . '/download/' . $fileName . '.xls',
        ]);
    }

    /**
     * 生成海报 的 小程序码
     */
    public function getShareCode()
    {
        $userInfo = $this->request->user_info;
        $path = input('path', '', 'trim');
        $scene = input('scene', '', 'trim');
        $wechat = new \Wechat();
        $re = $wechat->getUnlimitQRCode($path, $scene);

        $imageManager = new ImageManager();
        $image = $imageManager->make($re)->resize(430, 430);

        $head = 'https://douxiangtuan-1312696603.cos.ap-shanghai.myqcloud.com/default.jpeg';
        if ($userInfo->portrait) {
            $head = $userInfo->portrait;
        }
        $avatar = file_get_contents($head);
        $portrait = $imageManager->make(yuanImg($avatar))->resize(190, 190);

        $image->insert($portrait, 'left-top', 120, 120);
        $filePath = 'qrcode/';
        $filename = date('YmdHis') . Str::random(6) . '.png';
        $image->save($filePath . $filename);

        return success(['qr' => request()->domain() . '/' . $filePath . $filename]);
    }

    /**
     * 添加商户进入商圈
     */
    public function addShopToDistrict()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user_id = $this->request->uid;
        $businessDistrict = BusinessDistrictAdmin::where('user_id', $user_id)->find();
        if (!$businessDistrict) {
            return error('该用户不是商圈管理人');
        }
        $shop_info = \app\common\model\Shop::find($param['shop_id']);
        if (!$shop_info) {
            return error('店铺信息异常');
        }
        if ($shop_info->district_id != 0) {
            if ($shop_info->district_id == $businessDistrict->district_id) {
                return error('该店铺已在商圈中,无需添加');
            }
            return error('该店铺已经在其他商圈中');
        }
        $shop_info->district_id = $businessDistrict->district_id;
        $shop_info->save();
        return success('添加成功');
    }

    /**
     * 店铺管理
     */
    public function shopList()
    {
        $user_id = $this->request->uid;
        $shopIdList = ShopManage::where('status', 1)
            ->where('user_id', $user_id)
            ->column('shop_id');
        $shopList = \app\common\model\Shop::where('id', 'in', $shopIdList)->select();
        return success($shopList);
    }

    /**
     *  店铺管理 -- 店铺详情
     */
    public function shopDetail2()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user_id = $this->request->uid;
        $user_info = $this->request->user_info;
        $shop_id = $param['shop_id'];

        $re = ShopManage::where('user_id', $user_id)->where('shop_id', $shop_id)
            ->where('status', 1)->find();
        if (!$re) {
            return error('当前用户没有权限');
        }
        if (!in_array(1, explode(',', $re['function_arr']))) {
            return error('当前用户没有权限');
        }

        $shop = \app\common\model\Shop::with('banner')->find($shop_id)->toArray();
        //判断店铺 是否 连锁 /商圈
        $shop['flag'] = -1;
        $shop['flag_name'] = '';
        if ($shop['district_id'] != 0) {
            $re = BusinessDistrict::find($shop['district_id']);
            if ($re) {
                $shop['flag'] = $re->type;
                $shop['flag_name'] = $re->name;
            }
        }
        $list = [];
        foreach ($shop['banner'] as $v) {
            $list[] = $v['img'];
        }
        $shop['banner'] = $list;
        if (!$shop) {
            return error('店铺信息异常');
        }
        return success($shop);
    }

    /**
     * 店铺信息修改
     */
    public function shopDetailUpdate()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $user_id = $this->request->uid;
        $shop_id = $param['shop_id'];
        //判断权限
        $re = ShopManage::where('user_id', $user_id)->where('shop_id', $shop_id)
            ->where('status', 1)->find();
        if (!$re) {
            return error('当前用户没有权限');
        }
        if (!in_array(1, explode(',', $re['function_arr']))) {
            return error('当前用户没有权限');
        }

        $shop = \app\common\model\Shop::find($shop_id);
        if (!$shop) {
            return error('店铺信息异常');
        }
        if (isset($param['name'])) {
            $shop->setAttr('name', $param['name']);
        }
        if (isset($param['logo'])) {
            $shop->logo = $param['logo'];
            $shop->share_logo = '';
        }
        //更新联系方式
        if (isset($param['phone'])) {
            $shop->phone = $param['phone'];
        }
        if (isset($param['show_img'])) {
            $shop->show_img = $param['show_img'];
        }
        if (isset($param['txt_flag'])) {
            $shop->txt_flag = $param['txt_flag'];
        }
        if (isset($param['address']) && $param['address']) {
            $shop->address = $param['address'];
        }
        if (isset($param['longitude'])) {
            $shop->longitude = $param['longitude'];
        }
        if (isset($param['latitude'])) {
            $shop->latitude = $param['latitude'];
        }
        if (isset($param['remark'])) {
            $shop->remark = $param['remark'];
        }
        if (isset($param['self_name'])) {
            $shop->self_name = $param['self_name'];
        }
        if (isset($param['share_name'])) {
            $shop->share_name = $param['share_name'];
        }
        if (isset($param['platform_name'])) {
            $shop->platform_name = $param['platform_name'];
        }
        if (isset($param['name1'])) {
            if (mb_strlen($param['name1']) > 15) {
                return error('商家自定义标题不要超过15个字');
            }
            $shop->name1 = $param['name1'];
        }
        if (isset($param['banner'])) {
            ShopBanner::where('shop_id', $shop_id)->useSoftDelete('delete_time', time())->delete();
            foreach ($param['banner'] as $v) {
                ShopBanner::create([
                    'shop_id' => $shop_id,
                    'img'     => $v,
                    'status'  => 1
                ]);
            }
        } else {
            ShopBanner::where('shop_id', $shop_id)->useSoftDelete('delete_time', time())->delete();
        }
        if (isset($param['wechat'])) {
            $shop->wechat = $param['wechat'];
        }
        $shop->save();
        return success($shop);
    }

    /**
     * 店铺管理员管理
     */
    public function shopAdminList()
    {
        $user_id = $this->request->uid;
        $user_info = $this->request->user_info;
        //判断权限
        $re = ShopManage::where('user_id', $user_id)->where('status', 1)->select();
        if (!$re) {
            return error('当前用户没有权限');
        }
        $shopIdList = [];
        $dataList = [];
        foreach ($re as $v) {
            if (in_array(2, explode(',', $v['function_arr']))) {
                $shopIdList[] = $v['shop_id'];
            }
        }
        //根据店铺id列表获取所有员工
        if ($shopIdList) {
            $dataList = ShopManage::with([
                'user_info' => function ($query) {
                    return $query->field('id,nickname,portrait,phone');
                },
                'shop_info' => function ($query) {
                    return $query->field('id,name');
                }
            ])->where('shop_id', 'in', $shopIdList)
                ->where('role', '<>', 1)
                ->where('user_id', '<>', $user_id)
                ->select();
        }
        return success($dataList);
    }


    /**
     * 店铺工作人员  退出当前店铺
     * 0824
     */
    public function shopExit()
    {
        //获取用户信息
        $userId = $this->request->uid;
        //查询当前用户所属店铺
        //查询用户 相关店铺权限
        $manage = ShopManage::where('user_id', $userId)->select();
        $id = [];
        if ($manage->isEmpty()) {
            return error('当前用户没有操作权限');
        }
        foreach ($manage as $v) {
            if ($v->role != 1) {
                $id[] = $v->id;
            }
        }
        if (!$id) {
            return error('当前用户是场所所有人');
        }
        //退出商圈
        ShopManage::where('id', 'in', $id)->update(['delete_time' => time()]);
        return success([], '退出成功');
    }

    /**
     * 当前用户店铺信息
     */
    public function shopMeInfo()
    {
        $userInfo = $this->request->user_info;
        $admin = ShopManage::with('shop_info')->where('user_id', $userInfo->id)->find();

        switch ($admin->role) {
            case 1:
                $admin->role_name = '场所所有人';
                break;
            case 2:
                $admin->role_name = '店长';
                break;
            case 3:
                $admin->role_name = '店员';
                break;
            default:
                $admin->role_name = '异常';
                break;
        }
        $data = ['user_info' => $userInfo, 'shop_info' => $admin];
        return success($data);
    }

    /**
     * 店铺管理员 添加
     */
    public function shopManageAdd()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id'    => 'require|number',
            'phone|手机号'      => 'require|mobile',
            'role|角色'         => 'require|number',
            'function_arr|功能' => 'require'
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        //判断权限
        $user_id = $this->request->uid;
        $shop_id = $param['shop_id'];
        //判断权限
        $re = ShopManage::where('user_id', $user_id)->where('shop_id', $shop_id)
            ->where('status', 1)->find();
        if (!$re) {
            return error('当前用户没有权限');
        }
        if (!in_array(2, explode(',', $re['function_arr']))) {
            return error('当前用户没有权限');
        }
        //查找手机号 获取用户
        $user = User::where('phone', $param['phone'])->find();
        if (!$user) {
            return error('当前手机号未注册');
        }
        //判断用户是否已存在
        $re = ShopManage::where('user_id', $user->id)->find();
        if ($re) {
            return error('当前手机号用户已经是其他店铺的管理员');
        }
        //判断赋予的权限 是否超出 当前管理员权限

        ShopManage::create([
            'user_id'      => $user->id,
            'shop_id'      => $shop_id,
            'role'         => $param['role'],
            'function_arr' => $param['function_arr'],
            'status'       => 1,
            'remark'       => '由user_id=' . $user_id . '创建用户'
        ]);
        return success([], '添加成功');
    }

    /**
     * 更新管理员信息
     */
    public function shopManageUpdate()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'id|列表id'         => 'require|number',
            'role|角色'         => 'require|number',
            'function_arr|功能' => 'require',
            'status|状态'       => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $re = ShopManage::find($param['id']);
        if (!$re) {
            return error('信息异常!');
        }
        if ($re->role == 1) {
            return error('超管的信息不能修改!');
        }
        //判断权限
        $user_id = $this->request->uid;
        $shop_id = $re->shop_id;
        //判断权限
        $a = ShopManage::where('user_id', $user_id)->where('shop_id', $shop_id)->find();
        if (!$a) {
            return error('当前用户没有权限');
        }
        if (!in_array(2, explode(',', $a['function_arr']))) {
            return error('当前用户没有权限');
        }

        //更新信息
        $re->role = $param['role'];
        $re->function_arr = $param['function_arr'];
        $re->remark = $re->remark . "|由用户user_id:" . $user_id . "修改信息";
        $re->status = $param['status'];
        $re->save();
        return success([], '更新成功!');
    }

    /**
     * 删除管理员信息
     */
    public function shopManageDelete()
    {
        $param = $this->request->param();
        $validate = new Validate();
        $validate->rule([
            'id|列表id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $re = ShopManage::find($param['id']);
        if (!$re) {
            return error('信息异常!');
        }
        if ($re->role == 1) {
            return error('超管的信息不能修改!');
        }
        //判断权限
        $user_id = $this->request->uid;
        $shop_id = $re->shop_id;
        //判断权限
        $a = ShopManage::where('user_id', $user_id)->where('shop_id', $shop_id)->find();
        if (!$a) {
            return error('当前用户没有权限');
        }
        if (!in_array(2, explode(',', $a['function_arr']))) {
            return error('当前用户没有权限');
        }
        //更新信息
        $re->remark = $re->remark . '|由user_id:' . $user_id . '删除';
        $re->delete_time = time();
        $re->save();
        return success([], '删除成功!');
    }

    /**
     * 生成店铺海报
     */
    public function sharePost()
    {
        $param = $this->request->param();; //接收值
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shop = \app\common\model\Shop::find($param['shop_id']);
        if (!$shop) {
            return error('店铺信息异常');
        }
        $imageManager = new ImageManager();
        //商品海报模板
        $image = $imageManager->make(public_path() . 'poster.png')->resize(660, 961);
        //商品主图
        $product = $imageManager->make($shop->logo);
        if ($product->height() > $product->width()) {
//            $product = $product->heighten(600)->crop(600, 600, 0, (int)(($product->height() - 600) / 2));
            $product = $product->heighten(600);
            $image->insert($product, 'left-top', (int)((660 - $product->width()) / 2), 30);
        } else {
//            $product = $product->widen(600)->crop(600, 600, (int)(($product->width() - 600) / 2), 0);
            $product = $product->widen(600);
            $image->insert($product, 'left-top', 30, (int)((600 - $product->height()) / 2));
        }
//        $image->insert($product, 'left-top', 30, 30);
        //第三张是小程序码
        $wechat = new \Wechat();
        $re = $wechat->getUnlimitQRCode('pages/home/store', 'id=' . $shop->id);
        $image3 = $imageManager->make($re)->resize(200, 200);

        //先插入一个圆形白色图片
        $white = $imageManager->make(public_path() . 'white.jpg')->resize(90, 90);
        $image3 = $image3->insert(yuanImg($white->encode()->getEncoded()), 'left-top', 55, 55);
        //再插入店铺logo
        if ($product->height() > $product->width()) {
            $product = $product->widen(90)->crop(90, 90, 0, (int)(($product->height() - 90) / 2));
        } else {
            $product = $product->heighten(90)->crop(90, 90, (int)(($product->width() - 90) / 2), 0);
        }

        $image3 = $image3->insert(yuanImg($product->encode()->getEncoded()), 'left-top', 55, 55);

        $image->insert($image3, 'right-bottom', 29, 58);

        //商品标题
        $title = $shop->name;

        $image->text(mb_substr($title, 0, 12), 35, 785, function ($font) {
            $font->file(public_path() . 'font/heiya.ttf');
            $font->size(30);
            $font->valign('left');
        });

        if (mb_substr($title, 12, 14)) {
            $image->text(mb_substr($title, 12, 14), 35, 830, function ($font) {
                $font->file(public_path() . 'font/heiya.ttf');
                $font->size(30);
                $font->valign('left');
            });
        }

//        $image->save('a.jpg');
        $image = $image->encode('jpg', 100);
        $base64_encode = 'data:image/jpg;base64,' . base64_encode($image);
        $image->destroy();
        return success(['img_base64' => $base64_encode]);
    }

    /**
     * 2023-12-05
     * 丁一
     * 店铺会员列表
     * 根据店铺赠送出去积分记录来搜索用户,但凡获得过该店铺积分的用户都视为该店铺会员.
     */
    public function shopUserList()
    {
        $param = $this->request->param();; //接收值
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        if (!isset($param['page_size'])) {
            $param['page_size'] = 6;
        }
        [$pageSize, $pageNo] = paginate($param);
        $shopId = $param['shop_id'];
        $userId = $this->request->uid;
        //鉴权 查看当前用户是否有权限查看会员列表
        $a = ShopManage::where([
            'user_id' => $userId,
            'shop_id' => $shopId,
            'status'  => 1
        ])->find();
        if (!$a) {
            return error('当前用户权限不足');
        }

        //查询店铺赠送积分记录,获取用户id列表
        $userIdList = PointsLog::where('shop_id', $shopId)->where(['type' => 1, 'flag' => 1])->column('user_id');
        $userIdList = array_unique($userIdList);
        //查询用户信息,并做好分页
        $userList = User::where('id', 'in', $userIdList)
            ->where('status', 1)
            ->limit($pageSize * $pageNo, $pageSize)
            ->field('id,nickname,portrait,phone')
            ->select();

        $pointLogModel = new PointsLog();
        foreach ($userList as &$v) {
            //总获取
            $get_num = $pointLogModel::where('shop_id', $shopId)
                ->where('user_id', $v['id'])
                ->where('type', 1)
                ->sum('num');

            //总共花销总数
            $cost_num = $pointLogModel::where('shop_id', $shopId)
                ->where('user_id', $v['id'])
                ->where('type', 2)
                ->sum('num');
            $v['get_points'] = $get_num;
            $v['cost_points'] = $cost_num;
            $v['points'] = $get_num - $cost_num;
        }
        return success($userList);
    }

    /**
     * 获取店铺分享图片
     */
    public function getShopShareImg()
    {
        $param = $this->request->param();; //接收值
        $validate = new Validate();
        $validate->rule([
            'shop_id|店铺id' => 'require|number',
        ]);
        if (!$validate->check($param)) {
            return error($validate->getError());
        }
        $shop = \app\common\model\Shop::find($param['shop_id']);
        if (!$shop) {
            return error('店铺信息异常');
        }
        if ($shop->share_logo) {
            return success(['img' => $shop->share_logo]);
        }
        $imageManager = new ImageManager();
        $img = $imageManager->canvas(500, 400, '#FFFFFF');

        $product = $imageManager->make($shop->logo);
        if ($product->height() > $product->width()) {
            $product = $product->heighten(400);
            $img->insert($product, 'left-top', (int)((500 - $product->width()) / 2), 0);
        } else {
            $product = $product->widen(500);
            $img->insert($product, 'left-top', 0, (int)((400 - $product->height()) / 2));
        }
        $fileName = 'b.jpg';
        $img->save($fileName, 70);
        $img->destroy();
        $file = new UploadedFile($fileName, $fileName);
        $uploadConfig = sysconfig('upload');
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($uploadConfig['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($file)
                ->save();
        } catch (\Exception $e) {
            return error($e->getMessage());
        }
        if ($upload['save'] == true) {
            $shop->share_logo = $upload['url'];
            $shop->save();
            @unlink($fileName);
            return success(['img' => $upload['url']]);
        }
        return error('获取失败,请联系管理员');
    }

}